package osirix.ce;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import osirix.ce.enumerados.EAction;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class CEActivity extends Activity implements OnClickListener, Runnable {
	private static final int TIMEOUT_MILLISEC = 100;
	private EditText usuario;
	private EditText password;
	// bandera para identificar si el usuario se autentic� correctamente,
	// solamente se pone en true cuando se valida correctamente
	private Boolean flagUser = false;
	private ProgressDialog progressDialog;
	// contexto global de la app
	private SessionCE objSession;

	private UtilSQLite objUtilSql;

	String pass = "";

	private ProgressDialog pd;
	private Location currentLocation;
	private LocationManager mLocationManager;
	private LocationListener locationListener;
	private String accion;

	// private Context context;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Se instacian los Botones
		Button btnLogin = (Button) findViewById(R.id.btnLogin);
		btnLogin.setOnClickListener(this);

		// se obtiene el handler de las cajas de texto a las variables de esta
		// Actitivity
		usuario = (EditText) findViewById(R.id.txtUser);
		password = (EditText) findViewById(R.id.txtPass);

		// instanciamos el contexto de sessión de la aplicación
		objSession = ((SessionCE) getApplicationContext());
		writeSignalGPS();

		
		  //Pendiente probar BD Local  
		  
		  try { 
			  UtilSQLite objUtilSql = new UtilSQLite(this);
			  objUtilSql.createDataBase();
			  objUtilSql.open();
			  
			  
			  //objUtilSql.guardarComparendo(); 
			  
			  objUtilSql.leer();
			  
			  objUtilSql.close();
		  
		  } 
		  
		  catch (IOException e) {
			  Log.d("ErrorCE", "Prueba SQLite: " + e.getMessage());
			  
		  }
			  // TODO  Auto-generated 
			  
			  	  
		  
		 

	}

	private void writeSignalGPS() {

		DialogInterface.OnCancelListener dialogCancel = new DialogInterface.OnCancelListener() {

			public void onCancel(DialogInterface dialog) {
				Toast.makeText(
						getBaseContext(),
						getResources().getString(R.string.gps_signal_not_found),
						Toast.LENGTH_LONG).show();
				// handler.sendEmptyMessage(0);
			}

		};
		pd = ProgressDialog.show(this,
				this.getResources().getString(R.string.search), this
						.getResources().getString(R.string.search_signal_gps),
				true, true, dialogCancel);
		accion = "2";
		Thread thread = new Thread(this);
		thread.start();

	}

	public void onClick(View v) {

		// progressDialog = ProgressDialog.show(this, "", "Conectando...");
		// revisar esto, cuando entro siempre a esta activity deber�a limpiar
		// objetos UI y de codigo
		this.flagUser = false;
		// TODO Auto-generated method stub
		Log.d("pruebaLog", "Entr� Click BOtones");

		// esconde el teclado si esta desplegado
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(password.getWindowToken(), 0);
		// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

		// encriptaci�n del password

		try {
			pass = Util.SHA1(password.getText().toString());
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

		switch (v.getId()) {
		case R.id.btnLogin:
			// this.mtdLoginGet(usuario.getText().toString(), pass);
			// ponemos el ProgressDialog

			progressDialog = ProgressDialog.show(this, "Iniciando Sesión",
					"Por favor, espere", true, true);
			accion = "1";
			Thread thread = new Thread(this);
			thread.start();
			break;
		default:
			break;
		}

	}

	private void mtdLogin() {

		try {
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					TIMEOUT_MILLISEC);
			HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
			//
			HttpParams p = new BasicHttpParams();
			// p.setParameter("name", pvo.getName());
			p.setParameter("user", "1");

			// Instantiate an HttpClient
			HttpClient httpclient = new DefaultHttpClient(p);
			String url = "http://www.osirix.co/webservice/?";
			HttpPost httppost = new HttpPost(url);
			// HttpGet httpget = new HttpGet(url);

			// Instantiate a GET HTTP method
			try {
				Log.i(getClass().getSimpleName(), "send  task - start");
				//
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
						2);

				nameValuePairs.add(new BasicNameValuePair("a", "1"));
				nameValuePairs.add(new BasicNameValuePair("u", "prueba"));
				nameValuePairs.add(new BasicNameValuePair("c", "123456"));

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				ResponseHandler<String> responseHandler = new BasicResponseHandler();
				String responseBody = httpclient.execute(httppost,
						responseHandler);
				// Parse
				JSONObject json = new JSONObject(responseBody);
				JSONArray jArray = json.getJSONArray("posts");

				ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

				for (int i = 0; i < jArray.length(); i++) {
					HashMap<String, String> map = new HashMap<String, String>();
					JSONObject e = jArray.getJSONObject(i);
					String s = e.getString("post");

					JSONObject jObject = new JSONObject(s);

					map.put("Id", jObject.getString("Id"));
					map.put("usuario", jObject.getString("usuario"));
					// map.put("contrasena", jObject.getString("FullName"));
					map.put("nombre", jObject.getString("nombre"));

					map.put("apellido", jObject.getString("apellido"));
					map.put("tipodocumento", jObject.getString("tipodocumento"));
					map.put("numerodocumento",
							jObject.getString("numerodocumento"));

					mylist.add(map);

				}
				Toast.makeText(this, mylist.get(0).get("apellido"),
						Toast.LENGTH_LONG).show();

			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		catch (Throwable t) {
			Toast.makeText(this, "Request failed: " + t.toString(),
					Toast.LENGTH_LONG).show();
		}

	}

	private void wait(final String usu, final String usuPassword) {

		new Thread() {

			public void run() {
				// TODO Auto-generated method stub
				try {
					Looper.prepare();

					// sleep(10000);
					mtdLoginGet(usu, usuPassword);

					Looper.loop();
					Looper.myLooper().quit();
					// progressDialog.dismiss();
				} catch (Exception e) {
					Log.e("Osirix", e.getMessage());

				}
				progressDialog.dismiss();
				Log.d("Osirix", "fin thread de espera");

			}
		}.start();
		// thread.start();

		try {
			Thread.sleep(4500);
			this.mtdProbando();
			// writeSignalGPS();

		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// _____fin
	}

	private void mtdProbando() {
		// revisamos el valor de la bandera del user, para saber si se autentico
		// correctamente.
		if (this.flagUser) {
			Looper.prepare();
			Toast.makeText(this, "USUARIO VALIDADO CORRECTAMENTE",
					Toast.LENGTH_LONG).show();
			
			// Se registra la sesión en la BD
			// writeSignalGPS();

			// Abrir una nueva Activity
			this.finish();
			Intent intent = new Intent(this, MenuActivity.class);
			startActivity(intent);
			Looper.loop();
			Looper.myLooper().quit();
		} else {
			Looper.prepare();
			Toast.makeText(this, "USUARIO INCORRECTO", Toast.LENGTH_LONG)
					.show();
			Looper.loop();
			Looper.myLooper().quit();
			usuario.setText("");
			password.setText("");
			usuario.requestFocus();
			
		}
	}

	private void mtdLoginGet(String user, String pass) {

		String prueba = EAction.valueOf("AUTE").toString(); //revisar
		HashMap val = new HashMap<String, String>();
		
		val.put("usuario", user);
		val.put("password", pass);
		
		UtilWs.getWebService(val, EAction.AUTE.toString());
		
		// se prepara la solicitud del tipo Request HtppGet
		String urlWs = "http://webservice.osirix.co/?";
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget; // = new HttpGet("http://webservice.osirix.co/");
		HttpResponse response;

		// lista de parametros, para agregarlos al string de la ruta del WS
		List<NameValuePair> params = new LinkedList<NameValuePair>();
		//Time time = new Time(Long.toString(currentLocation.getTime()));
		//time.toString();
		
		if(currentLocation != null && Double.toString(currentLocation.getLatitude()) != null && Double.toString(currentLocation.getLatitude()) != ""){
			
		
		params.add(new BasicNameValuePair("fecha", "" +Long
				.toString(currentLocation.getTime())));
//		params.add(new BasicNameValuePair("fecha", time.toString()));
		params.add(new BasicNameValuePair("latitud", Double
				.toString(currentLocation.getLatitude())));
		params.add(new BasicNameValuePair("longitud", Double
				.toString(currentLocation.getLongitude())));
		params.add(new BasicNameValuePair("a", "2"));
		params.add(new BasicNameValuePair("u", user));
		params.add(new BasicNameValuePair("c", pass));

		String stringParams = URLEncodedUtils.format(params, "utf-8");
		urlWs += stringParams;

		httpget = new HttpGet(urlWs);
		Log.i("OsirixCE", urlWs);
		// se ejecuta el Request
		try {
			response = httpclient.execute(httpget);
			// se verifica la respuesta a la solicitud
			Log.i("OsirixCE", response.getStatusLine().toString());

			HttpEntity entity = response.getEntity();
			if (entity != null) {

				InputStream instream = entity.getContent();
				String result = Util.convertStreamToString(instream);
				Log.i("OsirixCE", result);

				// A Simple JSONObject Creation
				JSONObject json = new JSONObject(result);
				Log.i("OsirixCE_JsonObjet", "<jsonobject>\n" + json.toString()
						+ "\n</jsonobject>");

				// A Simple JSONObject Parsing
				JSONArray nameArray = json.names();
				JSONArray valArray = json.toJSONArray(nameArray);

				// se recorre el Obejto JsonArray que contiene los datos de
				// respuesta del WS
				for (int i = 0; i < valArray.length(); i++) {
					Log.i("Praeda",
							"<jsonname" + i + ">\n" + nameArray.getString(i)
									+ "\n</jsonname" + i + ">\n" + "<jsonvalue"
									+ i + ">\n" + valArray.getString(i)
									+ "\n</jsonvalue" + i + ">");

					// se valida si el json 'error' tiene como valor '0' para
					// validar al usuario
					if (nameArray.getString(i).equals("error")
							&& valArray.getString(i).equals("0")) {
						this.flagUser = true;
					}
					// se busca y recorre el json que contiene los datos del
					// usuario logueado
					if (nameArray.getString(i).equals("datos")) {
						JSONObject objJson = new JSONObject(
								valArray.getString(i));
						objSession.setIdUsuario(objJson.getString("Id"));
						objSession.setNomUsu(objJson.getString("codUsuario"));
						objSession.setNombreUsuario(objJson
								.getString("nomUsuario")
								+ " "
								+ objJson.getString("apeUsuario"));
						objSession.setNumDocuUsuario(objJson
								.getString("numDocUsuario"));
					}
				}

				// A Simple JSONObject Value Pushing
				json.put("sample key", "sample value");
				Log.i("Praeda", "<jsonobject>\n" + json.toString()
						+ "\n</jsonobject>");

				// Closing the input stream will trigger connection release
				instream.close();
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
	}

	public void run() {
		// this.wait(usuario.getText().toString(), pass);

		if (accion.equals("1")) {
			this.mtdLoginGet(usuario.getText().toString(), pass);
			progressDialog.dismiss();
			this.mtdProbando();
		} else {
			mLocationManager = (LocationManager) getBaseContext().getSystemService(Context.LOCATION_SERVICE);

			locationListener = new LocationListener() {
				public void onLocationChanged(Location location) {
					// Called when a new location is found by the network
					// location provider.
					setCurrentLocation(location);
					pd.dismiss();
					mLocationManager.removeUpdates(locationListener);

					if (currentLocation != null) {
						Toast.makeText(
								getBaseContext(),
								"Latitud: "
										+ Double.toString(currentLocation
												.getLatitude())
										+ " Longitud: "
										+ Double.toString(currentLocation
												.getLongitude()),
								Toast.LENGTH_LONG).show();
						// datosComparendo.setLatitud(Double.toString(currentLocation.getLatitude()));
						// datosComparendo.setLongitud(Double.toString(currentLocation.getLongitude()));
					}
				}

				public void onStatusChanged(String provider, int status,
						Bundle extras) {
				}

				public void onProviderEnabled(String provider) {
					System.out.println("Si hay red");
				}

				public void onProviderDisabled(String provider) {
					// TODO Auto-generated method stub
					System.out.println("No hay red");					
				}

			};

		if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
			
				Looper.prepare();
				mLocationManager.requestLocationUpdates(
						LocationManager.NETWORK_PROVIDER, 0, 0,
						locationListener);
				Looper.loop();
				Looper.myLooper().quit();

			} else {
				Looper.prepare();
				pd.dismiss();
				Toast.makeText(
						getBaseContext(),
						getResources().getString(R.string.gps_signal_not_found),
						Toast.LENGTH_LONG).show();
				Looper.loop();
				Looper.myLooper().quit();

		}
		}
	}

	protected void grabarInicioSesion(String latitud, String longitud,
			List<NameValuePair> params) {
		String urlWs = "http://webservice.osirix.co/?";
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget; // = new HttpGet("http://webservice.osirix.co/");
		HttpResponse response;

		// lista de parametros, para agregarlos al string de la ruta del WS
		List<NameValuePair> params2 = new LinkedList<NameValuePair>();
		params.add(new BasicNameValuePair("a", "2"));
		params.add(new BasicNameValuePair("idUsuario", objSession
				.getIdUsuario()));
		params.add(new BasicNameValuePair("fecha", Long
				.toString(currentLocation.getTime())));
		params.add(new BasicNameValuePair("latitud", Double
				.toString(currentLocation.getLatitude())));
		params.add(new BasicNameValuePair("longitud", Double
				.toString(currentLocation.getLongitude())));

		String stringParams = URLEncodedUtils.format(params, "utf-8");
		urlWs += stringParams;

		httpget = new HttpGet(urlWs);
		Log.i("OsirixCE", urlWs);
		// se ejecuta el Request

		try {
			response = httpclient.execute(httpget);
			// se verifica la respuesta a la solicitud
			Log.i("OsirixCE", response.getStatusLine().toString());
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				InputStream instream = entity.getContent();
				String result = Util.convertStreamToString(instream);
				Log.i("OsirixCE", result);

				// A Simple JSONObject Creation
				JSONObject json = new JSONObject(result);
				Log.i("Praeda", "<jsonobject>\n" + json.toString()
						+ "\n</jsonobject>");

				// A Simple JSONObject Parsing
				JSONArray nameArray = json.names();
				JSONArray valArray = json.toJSONArray(nameArray);

				// se recorre el Objeto JsonArray que contiene los datos de
				// respuesta del WS
				for (int i = 0; i < valArray.length(); i++) {
					Log.i("Praeda",
							"<jsonname" + i + ">\n" + nameArray.getString(i)
									+ "\n</jsonname" + i + ">\n" + "<jsonvalue"
									+ i + ">\n" + valArray.getString(i)
									+ "\n</jsonvalue" + i + ">");

					// se valida si el json 'error' tiene como valor '0' para
					// validar al usuario
					if (nameArray.getString(i).equals("error")
							&& valArray.getString(i).equals("0")) {
						Toast.makeText(this, "Sesión Registrada con EXITO",
								Toast.LENGTH_LONG).show();
						// mostrarNotificacionGeneracionComparendoyEnvioCorreoExitoso();
					}
				}
				instream.close();
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//Toast.makeText(this, "Sesión Registrada con EXITO", Toast.LENGTH_LONG);
		Intent intent = new Intent(this, MenuActivity.class);
		startActivity(intent);
	}

	private void setCurrentLocation(Location loc) {
		currentLocation = loc;
	}

	public Location getCurrentLocation() {
		return currentLocation;
	}

}